<template>
  <div class="chat-container">
    <!-- 聊天消息列表区域 -->
    <div class="chat-messages" ref="chatMessagesRef" v-if="chatMessages.length > 0">
      <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.type]">
        <div class="message-wrapper">
          <div class="avatar">
            <el-avatar :size="40" :src="message.type === 'user' ? userAvatar : aiAvatar" />
          </div>
          <div class="message-content-wrapper">
            <div class="message-info">
              <span class="sender-name">{{ message.type === 'user' ? '我' : botName }}</span>
              <span class="message-time">{{ message.time }}</span>
            </div>
            <div class="message-content">
              <div class="content-text" v-html="md.render(message.content)">
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="loading" class="message ai">
        <div class="message-wrapper">
          <div class="avatar">
            <el-avatar :size="40" :src="aiAvatar" />
          </div>
          <div class="message-content-wrapper">
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入框区域 -->
    <div class="chat-input">
      <div class="input-wrapper">
        <el-input
          v-model="currentMessage"
          type="textarea"
          :rows="3"
          placeholder="发消息..."
          @keyup.enter.native.prevent="sendMessage"
          resize="none"
          class="chat-textarea"
        />
        <el-button type="primary" circle class="send-button" @click="sendMessage">
          <el-icon><Promotion /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import MarkdownIt from 'markdown-it'
import { Promotion } from '@element-plus/icons-vue' // 引入图标

const md = new MarkdownIt()
const props = defineProps({
  callback: {
    type: Function,
    required: true
  },
  botName: {
    type: String,
    required: true
  }
});
// 头像配置
const userAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
const aiAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 聊天消息列表
const chatMessages = ref([])

// 当前输入的消息
const currentMessage = ref('')

// 加载状态
const loading = ref(false)

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
}
let count = 0

// This function will be passed as the botResponseDisplayCallback
const displayBotMessagePart = (data) => {
  loading.value = false
  if(count == 0) {
    chatMessages.value.push({
      type: 'ai',
      content: data,
      time: getCurrentTime()
    })
  } else {
    const length = chatMessages.value.length
    if (length > 0 && chatMessages.value[length - 1].type === 'ai') {
      chatMessages.value[length - 1].content += data
    } else { // Should not happen if count > 0, but as a fallback
       chatMessages.value.push({
        type: 'ai',
        content: data,
        time: getCurrentTime()
      })
    }
  }
  count++
  // console.log('displayBotMessagePart', data) // Keep for debugging if needed
}

// This function will be passed as the initUserMsgDisplay callback
const displayUserMessage = (msg) => {
  chatMessages.value.push({
    type: 'user',
    content: msg,
    time: getCurrentTime()
  })
  loading.value = true // Show loading indicator for bot response
  count = 0 // Reset count for new bot message stream
  currentMessage.value = '' // Clear input field
}

const sendMessage = () => {
  if (!currentMessage.value || currentMessage.value.trim() === '') {
    return;
  }
  // Call the callback from index.vue, passing the user message text,
  // and the two functions responsible for updating chatMessages in this component.
  props.callback(currentMessage.value, displayUserMessage, displayBotMessagePart);
}

// 自动滚动到底部
const chatMessagesRef = ref(null)
const scrollToBottom = () => {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
  }
}

// 监听消息变化，自动滚动
watch(chatMessages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 表情面板（待实现）
const toggleEmojiPanel = () => {
  // TODO: 实现表情面板
}

// 暴露方法和数据给父组件
defineExpose({
  currentMessage,
  sendMessage
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: transparent;
  position: relative;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 16px 100px 16px; /* 底部留出输入框空间 */
  scroll-behavior: smooth;
}

.message {
  margin-bottom: 20px;
  width: 100%;
}

.message-wrapper {
  display: flex;
  gap: 12px;
  max-width: 85%;
}

.message.user .message-wrapper {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  flex-shrink: 0;
}

.message-content-wrapper {
  display: flex;
  flex-direction: column;
}

.message-info {
  margin-bottom: 6px;
  font-size: 12px;
  color: #999;
}

.sender-name {
  margin-right: 8px;
  font-weight: 500;
}

.message-content {
  position: relative;
}

.content-text {
  padding: 12px 16px;
  border-radius: 20px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  word-break: break-word;
  line-height: 1.5;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.message.user .content-text {
  background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%);
  color: white;
  border: none;
  border-bottom-right-radius: 6px;
}

.message.ai .content-text {
  background-color: #F2F2F7;
  color: #000;
  border: none;
  border-bottom-left-radius: 6px;
}

.chat-input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.input-wrapper {
  display: flex;
  align-items: flex-end;
  max-width: 100%;
  gap: 8px;
}

.chat-textarea {
  flex: 1;
}

.chat-textarea :deep(.el-textarea__inner) {
  border-radius: 20px;
  padding: 12px 16px;
  line-height: 1.4;
  min-height: 44px !important;
  max-height: 120px;
  border: 1px solid #E5E5EA;
  background-color: #F2F2F7;
  font-size: 16px;
  resize: none;
}

.chat-textarea :deep(.el-textarea__inner):focus {
  border-color: #007AFF;
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2);
}

.send-button {
  width: 44px;
  height: 44px;
  font-size: 18px;
  background: linear-gradient(135deg, #007AFF 0%, #5856D6 100%);
  border: none;
  border-radius: 22px;
  margin-bottom: 0;
  flex-shrink: 0;
}

.send-button:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

/* Typing indicator styles */
.typing-indicator {
  display: flex;
  padding: 12px 16px;
  background: #fff;
  border-radius: 16px;
  border-top-left-radius: 4px;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background: #90959f;
  border-radius: 50%;
  margin: 0 2px;
  display: inline-block;
  animation: bounce 1.3s linear infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.15s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.3s;
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-4px);
  }
}
</style>